package com.imy.accessibility.node;

import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.imy.accessibility.CoreService;
import com.imy.accessibility.NodeInfoAccessibilityService;
import com.imy.accessibility.R;
import com.imy.accessibility.bean.CustomNode;
import com.imy.common.event.FloatingEvent;
import com.imy.common.util.ALog;
import com.imy.common.util.RefInvoke;
import com.imy.common.util.ToastUtil;
import com.imy.common.util.UiUtil;
import com.imy.lua.lib.node.UDRule;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class NodeActivity extends AppCompatActivity {

    public static final String NODE_KEY = "node";
    public static final String PATH_KEY = "path";
    public static final String ORI = "ori";
    private ImageView screenIv;
    private NodeContentView nodeContentView;

    private FloatingView mFloatingView;
    private FindByView mFindByView;
    private List<CustomNode> customNodeList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //设置横竖屏
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
            setNotchParams();
        }
        super.onCreate(savedInstanceState);
        hideSystemNav();
        setContentView(R.layout.activity_node);
        screenIv = findViewById(R.id.screen_iv);
        nodeContentView = findViewById(R.id.node_content_view);
        mFloatingView = findViewById(R.id.floating_view);
        mFindByView = findViewById(R.id.find_by_view);
//    AccessibilityNodeInfo nodeInfo = getIntent().getParcelableExtra(NODE_KEY);
        Bitmap bitmap = BitmapFactory.decodeFile(getPath());
        screenIv.setImageBitmap(bitmap);
        //这里就要开始替换node信息了
        //        copyNewNode(nodeInfo);

        //node 转换list
        CustomNode mNode = NodeInfoAccessibilityService.mNode;
        getNodeToList(mNode);
        customNodeList.add(mNode);
        ALog.ti("一共有多少个节点:" + customNodeList.size());
        mFloatingView.setFloatingListener(new FloatingView.FloatingListener() {
            @Override
            public void onClicked() {
                //弹出输入框
                mFindByView.show();

            }
        });
        mFindByView.setFindByListener(new FindByView.FindByListener() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onSearch(UDRule udRule) {
                if (udRule.className != null) {
                    if (TextUtils.isEmpty(udRule.text)
                            && TextUtils.isEmpty(udRule.id)) {
                        ToastUtil.toast(NodeActivity.this, R.string.find_class_need_other_one);
                        return;
                    }
                }
                List<CustomNode> node = findNode(udRule);
                for (int i = 0; i < node.size(); i++) {
                    CustomNode customNode = node.get(i);
                    ALog.ti("i" + i + " name:" + customNode.mClassName + " screen:" + customNode.mBoundsInScreen);
                }

                nodeContentView.setNodeByList(node);
            }
        });

        nodeContentView.postDelayed(runnable, 100);
    }

    @SuppressLint("NewApi")
    private void setNotchParams() {
        //设置刘海屏
        try {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            getWindow().setAttributes(lp);
        }catch (Exception ignored){

        }
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            UDRule udRule = new UDRule();
            udRule.id("android:id/content");
            List<CustomNode> node = findNode(udRule);
            nodeContentView.setNodeByList(node);
        }
    };

    private void getNodeToList(CustomNode mNode) {
        for (int i = 0; i < mNode.getChildCount; i++) {
            CustomNode customNode = mNode.child.get(i);
            customNodeList.add(customNode);
            if (customNode.getChildCount > 0) {
                getNodeToList(customNode);
            }
        }
    }

    private List<CustomNode> findNode(UDRule udRule) {
        //
        String text = udRule.text;
        List<CustomNode> list = new ArrayList<>();
        if (!TextUtils.isEmpty(text)) {
            List<CustomNode> byText = findByText(text);
            list.addAll(byText);
        }
        if (!TextUtils.isEmpty(udRule.id)) {
            int size = list.size();
            if (size > 0) {
                return findId(list, udRule.id);
            }
            return findId(customNodeList, udRule.id);
        }
        return list;
    }

    private List<CustomNode> findId(List<CustomNode> list, String id) {
        List<CustomNode> customNodeList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            CustomNode customNode = list.get(i);
            if (!TextUtils.isEmpty(customNode.mViewIdResourceName)) {
                if (customNode.mViewIdResourceName.equals(id)) {
                    customNodeList.add(customNode);
                }
            }
        }
        return customNodeList;
    }

    private List<CustomNode> findByText(String text) {
        List<CustomNode> list = new ArrayList<>();
        for (int i = 0; i < customNodeList.size(); i++) {
            CustomNode customNode = customNodeList.get(i);
            if (customNode.mText != null && customNode.mText.toString().contains(text)) {
                list.add(customNode);
            }
        }
        return list;
    }

    private void copyNewNode(AccessibilityNodeInfo nodeInfo) {
        AccessibilityNodeInfo newOne = (AccessibilityNodeInfo) RefInvoke.createObject(nodeInfo.getClass());
        ALog.ti("newOne:" + newOne);
        RefInvoke.invokeInstanceMethod(newOne, "init", AccessibilityNodeInfo.class, nodeInfo);
        ALog.ti("newOne:" + newOne + " -->nodeInfo:" + nodeInfo);
    }

    private void hideSystemNav() {
        if (Build.VERSION.SDK_INT >= 19) {
            final View decorView = getWindow().getDecorView();
            final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flags);
            decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
                @Override
                public void onSystemUiVisibilityChange(int visibility) {
                    if (isFinishing()) {
                        return;
                    }
                    if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                        decorView.setSystemUiVisibility(getShowInputFlags());
                    } else if (visibility == 4) {
                        decorView.setSystemUiVisibility(flags);
                    }
                }
            });
        }

    }

    private int getShowInputFlags() {
        final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        return flags;
    }

    private String getPath() {
        return getIntent().getStringExtra(PATH_KEY);
    }

    @Override
    protected void onDestroy() {
        String path = getPath();
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        nodeContentView.removeCallbacks(runnable);
        CoreService.mService.resumeNodeNotify(); //恢复节点监听
        ALog.i(" NodeActivity onDestroy");
        EventBus.getDefault().post(FloatingEvent.create(FloatingEvent.ACTION_SHOW));
        super.onDestroy();
    }


}
